//
//  ChangePasswordController.swift
//  SCA
//
//  Created by tjun on 2025/9/6.
//

import UIKit

class ModifyPasswordController: BaseController {
    
    private var scrollView: UIScrollView!
    private var contentView: UIView!

    private let rules: [PasswordRule] = [
        PasswordRule(title: "必须包含字母".localizedString) { $0.range(of: "[A-Za-z]", options: .regularExpression) != nil },
        PasswordRule(title: "必须包含数字".localizedString) { $0.range(of: "[0-9]", options: .regularExpression) != nil },
        PasswordRule(title: "至少8个字符".localizedString) { $0.count >= 8 },
        PasswordRule(title: "必须包含符号".localizedString) { $0.range(of: "[^A-Za-z0-9]", options: .regularExpression) != nil }
    ]
    
    let oldPasswordTextField = LabeledTextField(tip: "请重新输入您的密码".localizedString)
    let passwordTextField = LabeledTextField()
    let confirmPasswordTextField = LabeledTextField(tip: "请重新输入您的密码。".localizedString)
    let otpTextField = LabeledTextField()

    private let confirmButton = MainButton(type: .system, title: "确认".localizedString, font: UIFontMake(16), textColor: .white)
    private lazy var validationView = PasswordValidationView(rules: rules)

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationBar.title = "更改密码".localizedString
        setupUI()
    }
    
    private func setupUI() {
        
        scrollView = UIScrollView(frame: CGRect(x: 0, y: navBarHeight, width: view.width, height: screenHeight - navBarHeight)).addTo(view)
        scrollView.keyboardDismissMode = .onDrag
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.contentInsetAdjustmentBehavior = .never
        
        let contentSize = CGSize(width: scrollView.width, height: scrollView.height)
        
        scrollView.contentSize = contentSize
        
        contentView = UIView().addTo(scrollView)
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.size.equalTo(contentSize)
        }
        
        oldPasswordTextField.titleAttributedText = "当前密码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        oldPasswordTextField.textField.keyboardType = .asciiCapable
        contentView.addSubview(oldPasswordTextField)
        oldPasswordTextField.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.right.equalToSuperview().inset(AppStyle.margin.left)
        }
        
        passwordTextField.titleAttributedText = "密码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        contentView.addSubview(passwordTextField)
        passwordTextField.textField.keyboardType = .asciiCapable
        passwordTextField.textField.addTarget(self, action: #selector(passwordChanged(_ :)), for: .editingChanged)
        passwordTextField.snp.makeConstraints { make in
            make.top.equalTo(oldPasswordTextField.snp.bottom).offset(10)
            make.left.right.equalTo(oldPasswordTextField)
        }
        
        validationView.addTo(contentView)
        validationView.snp.makeConstraints { make in
            make.top.equalTo(passwordTextField.snp.bottom).offset(6)
            make.left.right.equalTo(oldPasswordTextField)
        }
        
        confirmPasswordTextField.titleAttributedText = "确认密码*".localizedString.attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        confirmPasswordTextField.textField.keyboardType = .asciiCapable
        confirmPasswordTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        contentView.addSubview(confirmPasswordTextField)
        confirmPasswordTextField.snp.makeConstraints { make in
            make.top.equalTo(validationView.snp.bottom).offset(10)
            make.left.right.equalTo(oldPasswordTextField)
        }

        otpTextField.titleAttributedText = "2FA OTP*".attributedString(rangeString: "*", rangeColor: UIColorMake(0xFF0000))
        contentView.addSubview(otpTextField)
        otpTextField.textField.addTarget(self, action: #selector(textFieldDidChange(_ :)), for: .editingChanged)
        otpTextField.snp.makeConstraints { make in
            make.top.equalTo(confirmPasswordTextField.snp.bottom).offset(10)
            make.left.right.equalTo(oldPasswordTextField)
        }
        
        confirmButton.addTo(contentView)
        confirmButton.isEnabled = false
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
        confirmButton.snp.makeConstraints { make in
            make.left.right.equalTo(oldPasswordTextField)
            make.height.equalTo(AppStyle.size.buttonHeight.scaled)
            make.top.equalTo(otpTextField.snp.bottom).offset(30)
        }
        
    }

    @objc func textFieldDidChange(_ sender: UITextField) {
        if let oldPassword = oldPasswordTextField.textField.text,
           let password = passwordTextField.textField.text,
           let confirmPassword = confirmPasswordTextField.textField.text,
           let otp = otpTextField.textField.text,
           isValidPassword(oldPassword),
           isValidPassword(password),
           password == confirmPassword,
           otp.count > 0 {
            confirmButton.isEnabled = true
        } else {
            confirmButton.isEnabled = false
        }
    }

    @objc private func passwordChanged(_ sender: UITextField) {
        validationView.validate(password: sender.text ?? "")
    }

    @objc func confirmButtonTapped() {
        guard let oldPassword = oldPasswordTextField.textField.text,
           let password = passwordTextField.textField.text,
           let otp = otpTextField.textField.text else {
            return
        }
        
        view.endEditing(true)

        HUD.showLoadingInView(self.view)
        MineService.changePassword(oldPassword: oldPassword, password: password, otf: otp) {
            HUD.hideHUD(for: self.view)
            NotificationCenter.default.post(name: NotificationName.userLogout, object: nil)
            guard let topViewController = topViewController() else {
                return
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
                let alert = Alert.alert(title: "温馨提示".localizedString, message: "重置密码成功".localizedString, preferredStyle: .alert)
                alert.addAction(title: "Ok") {}.showIn(topViewController)
            })
        }
    }
 
}

 

